package com.zhuifeng.smart.daoimpl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.zhuifeng.smart.dao.UserDao;
import com.zhuifeng.smart.model.User;
import com.zhuifeng.smart.util.JdbcUtil;

public class UserDaoImpl implements UserDao {
	private static QueryRunner runner = new QueryRunner(
			JdbcUtil.getDataSource());

	@Override
	public User addUser(User user) {
		String sql = "insert into user(userid,password,username) values(?,md5(?),?)";
		try {
			runner.insert(sql, new BeanHandler<User>(User.class), new Object[] {
					user.getUserid(), user.getPassword(), user.getUsername() });
			return this.getUser(user.getUserid());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public User getUser(String userId, String userPassword) {
		String sql = "select * from user where userid = ? and password = md5(?)";
		try {
			return runner.query(sql, new BeanHandler<User>(User.class),
					new Object[] { userId, userPassword });
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}

	@Override
	public User getUser(String userId) {
		String sql = "select * from user where userid = ?";
		try {
			return runner.query(sql, new BeanHandler<User>(User.class),
					new Object[] { userId });
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}

}
